package com.ftg.learn.pattern;



import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kangjx
 * @createTime 2022/11/28
 */
public class JdbcUtil {

    private String username = "root";
    private String password = "Love0913@kjx";
    private String url = "jdbc:mysql://localhost:3306/ad";

    public List<Map<String,Object>> query(String sql){
        List<Map<String,Object>> list = new ArrayList<>();

        try(
            Connection conn = DriverManager.getConnection(url,username,password);
            PreparedStatement stmt = conn.prepareStatement(sql);
        ){

            ResultSet rs =  stmt.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            while(rs.next()){
                Map<String,Object> map = new HashMap<>();
                for(int i = 0 ;i < rsmd.getColumnCount();i++){
                    map.put(rsmd.getColumnName(i + 1),rs.getObject(i + 1));
                }
                list.add(map);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return list;
    }

}
